//
//  MapViewController.m
//  dangdang
//
//  Created by air on 16/2/16.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "MapViewController.h"
#import <AMapNaviKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface MapViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate, UITextFieldDelegate, AMapSearchDelegate>
{
    MAMapView * _mapView;
    AMapLocationManager * _mapLocationManager;
    AMapSearchAPI * _search;
}

@property (nonatomic, strong) UILabel * firstLabel;
@property (nonatomic, strong) UITextField * secondTextField;
@property (nonatomic, strong) NSMutableArray *tips;
@property (nonatomic, copy) NSString * lng;
@property (nonatomic, copy) NSString * lat;
@property (nonatomic) CLLocationCoordinate2D coor1;
@property (nonatomic) CLLocationCoordinate2D coor2;
@property (nonatomic) NSInteger count;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _count = 0;
    
    _positionTextField.delegate = self;
    
    _tips = [NSMutableArray array];
    
    _currentPositionView.hidden = YES;
    
    [self configMapView];
    
    self.title = @"收货地址";
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configMapView
{
    _mapLocationManager = [[AMapLocationManager alloc] init];
    
    [_mapLocationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    [_mapLocationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        //        NSLog(@"location:%@", location);
        if (regeocode)
        {
            _currentPositionView.hidden = NO;
            _lng = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
            _lat = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
            _topLabel.text = [NSString stringWithFormat:@"当前位置:%@", regeocode.street];
            _bottomLabel.text = [NSString stringWithFormat:@"%@%@", regeocode.city, regeocode.district];
            
//            [_mapLocationManager startUpdatingLocation];
        }
    }];
    
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _mapView.delegate = self;
    _mapView.userTrackingMode = 1;
    _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    [_mapView setZoomLevel:16.1 animated:YES];
    
    UIView * topFirstView = [[UIView alloc] initWithFrame:CGRectMake(15, 79, self.view.bounds.size.width - 30, 45)];
    topFirstView.backgroundColor = [UIColor whiteColor];
    topFirstView.layer.borderWidth = 1;
    topFirstView.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 5, 35, 35)];
    imageView.image = [UIImage imageNamed:@"magnifying11.png"];
    [topFirstView addSubview:imageView];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeMapView)];
    tap.numberOfTapsRequired = 1;
    
    _firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(38, 0, topFirstView.bounds.size.width - 38, 45)];
    _firstLabel.font = [UIFont systemFontOfSize:16.0];
    [_firstLabel addGestureRecognizer:tap];
    _firstLabel.userInteractionEnabled = YES;
    [topFirstView addSubview:_firstLabel];
    
    UIView * topSecondView = [[UIView alloc] initWithFrame:CGRectMake(15, 139, self.view.bounds.size.width - 30, 45)];
    topSecondView.backgroundColor = [UIColor whiteColor];
    topSecondView.layer.borderWidth = 1;
    topSecondView.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
    
    _secondTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, topSecondView.bounds.size.width - 20, 45)];
    _secondTextField.font = [UIFont systemFontOfSize:16.0];
    _secondTextField.placeholder = @"请输入楼号门牌号等详细信息";
    _secondTextField.delegate = self;
    [topSecondView addSubview:_secondTextField];
    
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(15, self.view.bounds.size.height - 120, self.view.bounds.size.width - 30, 50)];
    [button addTarget:self action:@selector(returnKeyboardView) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor orangeColor];
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.layer.cornerRadius = 4;
    
    UIImageView * imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.center.x - 19, self.view.center.y - 37, 38.5, 38.5)];
    imageView2.image = [UIImage imageNamed:@"hk_address2.png"];
    [_mapView addSubview:imageView2];
    
    //    [self.view addSubview:_mapView];
    [_mapView addSubview:topFirstView];
    [_mapView addSubview:topSecondView];
    [_mapView addSubview:button];
    
}

- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
//    NSLog(@"long = %f, lat = %f", mapView.centerCoordinate.longitude, mapView.centerCoordinate.latitude);
//    CLLocationCoordinate2D touchMapCoordinate = [_mapView convertPoint:mapView.center toCoordinateFromView:_mapView];
    NSLog(@"count = %ld", _count);
    CLLocation * location = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
//    CLLocation * location = [[CLLocation alloc] initWithLatitude:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude];
    CLGeocoder * geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if (error == nil && [placemarks count] > 0) {
            
            //这时的placemarks数组里面只有一个元素
            
            CLPlacemark * placemark = [placemarks firstObject];
            //                NSLog(@"%@",placemark.addressDictionary);
//            NSLog(@"line = %@, name = %@, state = %@, street = %@, sub = %@, tho = %@",[placemark.addressDictionary objectForKey:@"FormattedAddressLines"], [placemark.addressDictionary objectForKey:@"Name"], [placemark.addressDictionary objectForKey:@"State"] ,[placemark.addressDictionary objectForKey:@"Street"],[placemark.addressDictionary objectForKey:@"SubLocality"],[placemark.addressDictionary objectForKey:@"Thoroughfare"]);
            if (_count > 2) {
                _firstLabel.text = [NSString stringWithFormat:@"%@", [placemark.addressDictionary objectForKey:@"Name"]];
                _lng = [NSString stringWithFormat:@"%f", mapView.centerCoordinate.longitude];
                _lat = [NSString stringWithFormat:@"%f", mapView.centerCoordinate.latitude];
                
                if ([_location isEqualToString:@"designated"]) {
                    _coor1 = CLLocationCoordinate2DMake(mapView.centerCoordinate.latitude,mapView.centerCoordinate.longitude);
                }else if ([_location isEqualToString:@"location"]){
                    _coor2 = CLLocationCoordinate2DMake(mapView.centerCoordinate.latitude,mapView.centerCoordinate.longitude);
                }
            }
        }
    }];
    _count ++;
}

- (void)removeMapView{
    _count = 1;
    [_mapView removeFromSuperview];
}

- (void)returnKeyboardView{
    if ([_location isEqualToString:@"designated"]) {
        if ([_secondTextField.text isEqualToString:@""] || [_secondTextField.text isEqual:nil]) {
            _KeyboardViewController.designatedLabel.text = [NSString stringWithFormat:@"%@", _firstLabel.text];
        }else{
            _KeyboardViewController.designatedLabel.text = [NSString stringWithFormat:@"%@-%@", _firstLabel.text, _secondTextField.text];
        }
        _KeyboardViewController.designatedLabel.textColor = [UIColor orangeColor];
        _KeyboardViewController.designatedLabel.font = [UIFont systemFontOfSize:16.0];
        
        _KeyboardViewController.coor1 = _coor1;
    }else if ([_location isEqualToString:@"location"]){
        if ([_secondTextField.text isEqualToString:@""] || [_secondTextField.text isEqual:nil]) {
            _KeyboardViewController.locationLabel.text = [NSString stringWithFormat:@"%@", _firstLabel.text];
        }else{
            _KeyboardViewController.locationLabel.text = [NSString stringWithFormat:@"%@-%@", _firstLabel.text, _secondTextField.text];
        }
        _KeyboardViewController.locationLabel.textColor = [UIColor orangeColor];
        _KeyboardViewController.locationLabel.font = [UIFont systemFontOfSize:16.0];
        
        _KeyboardViewController.lng = _lng;
        _KeyboardViewController.lat = _lat;
        
        _KeyboardViewController.coor2 = _coor2;
    }    

    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)currentPositionPush:(UIButton *)sender {
    _mapView.showsUserLocation = YES;
    
    NSString * string = [_topLabel.text substringFromIndex:5];
    _firstLabel.text = [NSString stringWithFormat:@"%@%@", _bottomLabel.text, string];
    [self.view addSubview:_mapView];
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay{
    return nil;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSString * str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [self searchTipsWithKey:str];
    
    return YES;
}

/* 输入提示 搜索.*/
- (void)searchTipsWithKey:(NSString *)key
{
    if (key.length == 0)
    {
        return;
    }
    
//    AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
//    tips.keywords = key;
//    NSLog(@"key = %@", key);
//    tips.city     = @"广州";
//    //    tips.cityLimit = YES; 是否限制城市
//    
//    [_search AMapInputTipsSearch:tips];
    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    
    request.keywords = key;
    request.city = @"广州";
    request.requireExtension = YES;
    [_search AMapPOIKeywordsSearch:request];
}

- (void)clearAndShowAnnotationWithTip:(AMapPOI *)tip{
        if (tip.uid != nil && tip.location != nil) /* 可以直接在地图打点  */
        {
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(tip.location.latitude, tip.location.longitude);
            [_mapView setCenterCoordinate:pointAnnotation.coordinate];
            [_mapView selectAnnotation:pointAnnotation animated:YES];
            [_mapView addAnnotation:pointAnnotation];
            
            if ([tip.district isEqual:tip.address]) {
                _firstLabel.text = [NSString stringWithFormat:@"%@(%@%@%@)", tip.name, tip.province, tip.city, tip.district];
            }else{
                _firstLabel.text = [NSString stringWithFormat:@"%@(%@%@%@%@)", tip.name, tip.province, tip.city, tip.district, tip.address];
            }
            [self.view addSubview:_mapView];
//            UIImageView * imageView = [UIImageView alloc] initWithFrame:<#(CGRect)#>;
//            annotationView.image = [UIImage imageNamed:@"hk_gps2.png"];
        }
}

#pragma mark - AMapSearchDelegate

///* 输入提示回调. */
//- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
//{
////    [self.tips setArray:response.tips];
//    [self.tips addObjectsFromArray:response.tips];
//    NSLog(@"tips = %@", self.tips);
//    
//    [self.tableView reloadData];
//}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    [self.tips setArray:response.pois];
    [self.tableView reloadData];
}

// 修改大头针图片
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    static NSString *reuseIndetifier = @"annotationReuseIndetifier";
    MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    if (annotationView == nil)
    {
        annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:reuseIndetifier];
    }
//    annotationView.image = [UIImage imageNamed:@"hk_address2.png"];
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
//    annotationView.centerOffset = CGPointMake(0, -18);
//    NSLog(@"width = %f, height = %f, x = %f, y = %f", annotationView.bounds.size.width, annotationView.bounds.size.height, annotationView.bounds.origin.x, annotationView.bounds.origin.y);
    
    return annotationView;
}

//-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
//updatingLocation:(BOOL)updatingLocation
//{
//    if(updatingLocation)
//    {
//        //取出当前位置的坐标
//    }
//}

#pragma mark UITableViewDataSource && Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    
    AMapPOI *tip = self.tips[indexPath.row];
    
    cell.textLabel.text = tip.name;
    
    if ([tip.district isEqual:tip.address]) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@", tip.province, tip.city, tip.district];
    }else{
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@%@", tip.province, tip.city, tip.district, tip.address];
    }
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AMapPOI *tip = self.tips[indexPath.row];
    
    _lng = [NSString stringWithFormat:@"%f", tip.location.longitude];
    _lat = [NSString stringWithFormat:@"%f", tip.location.latitude];
    
    if ([_location isEqualToString:@"designated"]) {
        _coor1 = CLLocationCoordinate2DMake(tip.location.latitude,tip.location.longitude);
    }else if ([_location isEqualToString:@"location"]){
        _coor2 = CLLocationCoordinate2DMake(tip.location.latitude,tip.location.longitude);
    }
    
    [_positionTextField resignFirstResponder];
    
    [self clearAndShowAnnotationWithTip:tip];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
